package org.xhnews.parsers;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Vector;

import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.IndexData;
import org.xhnews.utils.StringUtil;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class IndexDataPullXMLParser {

	public static Vector readIndexData(InputStream inputStream,
			String inputEncoding) throws Exception {
		XmlPullParserFactory pullParserFactory = XmlPullParserFactory
				.newInstance();
		XmlPullParser pullParser = pullParserFactory.newPullParser();
		Reader reader = new InputStreamReader(inputStream, inputEncoding);
		reader.read();
		pullParser.setInput(reader);
		int eventType = pullParser.getEventType();
		Vector items = null;
		IndexData item = null;

		try {
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					items = new Vector();
					break;
				case XmlPullParser.START_TAG:
					if ("item".equals(nodeName)) {
						item = new IndexData();
						item.setDate(StringUtil.string2Date(pullParser
								.getAttributeValue(2)));
						item.setIndex(Double.parseDouble(pullParser
								.getAttributeValue(1)));
						item.setLabel(pullParser.getAttributeValue(0));
					}
					break;
				case XmlPullParser.END_TAG:
					if ("item".equals(nodeName)) {
						items.addElement(item);
						item = null;
					}
					break;
				}
				eventType = pullParser.next();
			}// end while
			return items;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
}
